<!-- 新增/修改弹框 -->
<template>
  <!-- 新增/修改弹窗 -->
  <el-dialog
    v-model="dialogAddOrEdit.visible"
    :width="screenWidth"
    :fullscreen="mobile === 'mobile'"
    :title="dialogAddOrEdit.title"
    draggable
    close-icon="CloseBold"
    :close-delay="200"
    style="margin-top: 15vh"
    @close="closeDialog(false)"
  >
    <el-steps :active="active" finish-status="finish" simple>
      <el-step title="基础信息" :icon="Edit" />
      <el-step title="竣工报告" :icon="Document" />
      <el-step title="发放工资证明" :icon="Wallet" />
      <el-step title="完工承诺书" :icon="DocumentChecked" />
    </el-steps>
    <el-form
      v-show="active == 0"
      ref="baseFormRef"
      v-loading="loading"
      :model="formData"
      :rules="rules"
      label-width="120"
      size=""
      style="padding-right: 10px; overflow: auto"
    >
      <el-row justify="center" style="margin-top: 10px">
        <el-col :span="itemSpan">
          <el-form-item label="项目名称" prop="name">
            <el-input v-model="projectInfo.name" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="项目编号" prop="prjNum">
            <el-input v-model="projectInfo.prjNum" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="项目负责人" prop="name">
            <el-input v-model="projectInfo.linkMan" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="负责人联系电话" prop="name">
            <el-input v-model="projectInfo.linkPhone" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="合同开工日期" prop="name">
            <el-input v-model="projectInfo.contractStartDate" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan"> </el-col>
        <el-col :span="20">
          <el-form-item label="申请理由" prop="applyReason">
            <el-input
              v-model="formData.applyReason"
              type="textarea"
              style="width: 100%"
              :row="3"
              placeholder="请输入申请理由"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form
      v-show="active == 1"
      ref="completedFormRef"
      v-loading="loading"
      :model="formData"
      :rules="rules"
      label-width="170"
      size=""
      style="padding-right: 10px; overflow: auto"
    >
      <el-row justify="center" style="margin-top: 10px">
        <el-col :span="24">
          <el-form-item label="竣工初验报告" prop="attachments">
            <el-upload
              v-model:file-list="fileList"
              :action="actionUrl"
              :on-exceed="handleUploadExceed"
              :on-success="handleUploadSuccess"
              :limit="5"
              accept=".doc,.docx,.pdf,.jpg,.png,.xls,.xlsx"
            >
              <el-button plain size="small">上传附件</el-button>
              <!-- <DownloadTemplate :type=""></DownloadTemplate> -->
              <template #tip>
                <div class="el-upload__tip">仅支持上传doc,docx,xls,xlsx,pdf,jpg,png且不大于5M的文件</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="竣工报告" prop="attachments3">
            <el-upload
              v-model:file-list="fileList3"
              :action="actionUrl"
              :on-exceed="handleUploadExceed"
              :on-success="handleUploadSuccess"
              :limit="5"
              accept=".doc,.docx,.pdf,.jpg,.png,.xls,.xlsx"
            >
              <el-button plain size="small">上传附件</el-button>
              <!-- <DownloadTemplate :type=""></DownloadTemplate> -->
              <template #tip>
                <div class="el-upload__tip">仅支持上传doc,docx,xls,xlsx,pdf,jpg,png且不大于5M的文件</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form
      v-show="active == 2"
      ref="wageFormRef"
      v-loading="loading"
      :model="formData"
      :rules="rules"
      label-width="220"
      size=""
      style="padding-right: 10px; overflow: auto"
    >
      <el-row justify="center" style="margin-top: 10px">
        <el-col :span="24">
          <el-form-item label="无拖欠农民工工资证明" prop="attachments4">
            <el-upload
              v-model:file-list="fileList4"
              :action="actionUrl"
              :on-exceed="handleUploadExceed"
              :on-success="handleUploadSuccess"
              :limit="5"
              accept=".doc,.docx"
            >
              <el-button plain size="small">上传附件</el-button>
              <DownloadTemplate :type="107"></DownloadTemplate>
              <template #tip>
                <div class="el-upload__tip">仅支持上传doc,docx且不大于5M的文件</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="工程完工暨工资付清公示现场照片" prop="attachments5">
            <el-upload
              v-model:file-list="fileList5"
              :action="actionUrl"
              :on-exceed="handleUploadExceed"
              :on-success="handleUploadSuccess"
              :limit="5"
              accept=".doc,.docx"
            >
              <el-button plain size="small">上传附件</el-button>
              <DownloadTemplate :type="104"></DownloadTemplate>
              <template #tip>
                <div class="el-upload__tip">仅支持上传doc,docx且不大于5M的文件</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form
      v-show="active == 3"
      ref="promiseFormRef"
      v-loading="loading"
      :model="formData"
      :rules="rules"
      label-width="170"
      size=""
      style="padding-right: 10px; overflow: auto"
    >
      <el-row justify="start" style="margin-top: 10px">
        <el-col :span="24">
          <el-form-item label="项目完工承诺书" prop="attachments2">
            <el-upload
              v-model:file-list="fileList2"
              :action="actionUrl"
              :on-exceed="handleUploadExceed"
              :on-success="handleUploadSuccess"
              :limit="5"
              accept=".doc,.docx"
            >
              <el-button plain size="small">上传附件</el-button>
              <DownloadTemplate :type="108"></DownloadTemplate>
              <template #tip>
                <div class="el-upload__tip">仅支持上传doc,docx且不大于5M的文件</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog_footer">
        <el-button v-if="active >= 1" type="primary" :loading="loading" @click="handelPrev">上一步</el-button>
        <el-button v-if="active >= 0 && active < 3" type="primary" :loading="loading" @click="handelNext"
          >下一步</el-button
        >
        <el-button v-if="active == 3" type="primary" :loading="loading" @click="handleSubmit">{{
          dialogAddOrEdit.footBtn
        }}</el-button>
        <el-button @click="closeDialog(false)">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { AddProjectCompleted, UpdateProjectCompleted, GetProjectCompletedForm } from "@/api/project/completed/index";
import { ProjectCompletedEditForm, Int32AttachmentsForm } from "@/api/project/completed/types";
import { useScreen } from "@/store/modules/screen";
import { FormRules } from "element-plus/es/components/form/src/types";
import DownloadTemplate from "@/views/common/DownloadTemplate/index.vue";
import { Edit, DocumentChecked, Document, Wallet } from "@element-plus/icons-vue";
import type { UploadUserFile } from "element-plus";
import moment from "moment";

//声明变量
const actionUrl = ref(`${import.meta.env.VITE_APP_BASE_API}/api/v1/common/upload`);

const projectInfo = JSON.parse(localStorage.getItem("project") ?? "{}");

//上传文件列表
const fileList = ref<UploadUserFile[]>([]); //竣工初验报告
const fileList2 = ref<UploadUserFile[]>([]); //项目完工承诺书
const fileList3 = ref<UploadUserFile[]>([]); //竣工报告
const fileList4 = ref<UploadUserFile[]>([]); //无拖欠农民工工资
const fileList5 = ref<UploadUserFile[]>([]); //工程完工暨工资付清公示现场照片

const screenStore = useScreen();
const mobile = computed(() => screenStore.device);
const screenWidth = ref(900);
const itemSpan = ref(12);
const props = defineProps({
  dialogAddOrEdit: {
    type: Object,
    default: () => ({
      visible: false,
      title: "新增",
      footBtn: "确认新增",
      id: 0,
      type: 1, //1为停工 2 为复工
    }),
  },
});
const active = ref(0);
const { dialogAddOrEdit } = toRefs(props);
const emit = defineEmits(["sendClose"]);
const loading = ref(false);

const formData = reactive<ProjectCompletedEditForm>({});
const baseFormRef = ref(ElForm);
const promiseFormRef = ref(ElForm);
const wageFormRef = ref(ElForm);
const completedFormRef = ref(ElForm);

const fileMapType = new Map();
fileMapType.set(107, "竣工初验报告");
fileMapType.set(108, "竣工报告");
fileMapType.set(109, "项目完工承诺书");
fileMapType.set(110, "无拖欠农民工工资证明");
fileMapType.set(111, "工程完工暨工资付清公示现场照片");

const rules = reactive<FormRules<ProjectCompletedEditForm>>({
  applyReason: [{ required: true, message: "申请理由不能为空", trigger: "blur" }],
  endDate: [{ required: true, message: "实际竣工日期不能为空", trigger: "blur" }],
  attachments: [
    {
      trigger: "change",
      validator(_rule, _value, callback) {
        if (fileList.value.length === 0 && fileList3.value.length === 0) {
          callback(new Error("请上传竣工报告或竣工初验报告"));
        } else {
          callback();
        }
      },
    },
  ],
  attachments2: [
    {
      required: true,
      message: "请上传项目完工承诺书",
      trigger: "change",
      validator(_rule, _value, callback, _source, _options) {
        if (fileList2.value.length === 0) {
          callback(new Error("请上传项目完工承诺书"));
        } else {
          callback();
        }
      },
    },
  ],
  attachments3: [
    {
      trigger: "change",
      validator(_rule, _value, callback) {
        if (fileList.value.length === 0 && fileList3.value.length === 0) {
          callback(new Error("请上传竣工报告或竣工初验报告"));
        } else {
          callback();
        }
      },
    },
  ],
  attachments4: [
    {
      required: true,
      message: "请上传无拖欠农民工工资证明",
      trigger: "change",
      validator(_rule, _value, callback, _source, _options) {
        if (fileList4.value.length === 0) {
          callback(new Error("请上传无拖欠农民工工资证明"));
        } else {
          callback();
        }
      },
    },
  ],
  attachments5: [
    {
      required: true,
      message: "请上传工程完工暨工资付清公示现场照片",
      trigger: "change",
      validator(_rule, _value, callback, _source, _options) {
        if (fileList5.value.length === 0) {
          callback(new Error("请上传工程完工暨工资付清公示现场照片"));
        } else {
          callback();
        }
      },
    },
  ],
});

const disabledEndDate = (time: Date) => {
  if (projectInfo.contractStartDate) {
    return time.getTime() <= new Date(projectInfo.contractStartDate).getTime();
  }
  return time.getTime() > new Date(moment().format("YYYY-MM-DD")).getTime();
};

/**
 * 上一步
 */
const handelPrev = () => {
  active.value = active.value - 1;
};

/**
 * 下一步
 */
const handelNext = async () => {
  let validate = false;
  if (active.value == 0) {
    validate = await baseFormRef.value.validate();
  }
  if (active.value == 1) {
    validate = await completedFormRef.value.validate();
  }
  if (active.value == 2) {
    validate = await wageFormRef.value.validate();
  }
  if (active.value == 3) {
    validate = await promiseFormRef.value.validate();
  }
  if (!validate) return;
  ++active.value;
};

/* 附件上传 */
const handleUploadExceed = () => {
  ElMessage.error("最多上传5个附件");
};
const handleUploadSuccess = (response: any) => {
  if (response.type === 0) {
    if (response.success) {
    } else {
      ElMessage.error(response.msg);
    }
  } else {
    ElMessage.error(response.msg);
  }
};

watch(
  () => dialogAddOrEdit.value.visible,
  () => {
    if (dialogAddOrEdit.value.visible) {
      if (dialogAddOrEdit.value.id > 0) {
        GetProjectCompletedForm(dialogAddOrEdit.value.id).then((res) => {
          if (res.success) {
            Object.assign(formData, res.data);
            if (formData.dicAttachments && formData.dicAttachments[fileMapType.get(107)]) {
              res.data.dicAttachments[fileMapType.get(107)].forEach((item: any) => {
                fileList.value.push({
                  name: item.attachmentName,
                  status: "success",
                  uid: item.attachmentId,
                });
              });
            }
            if (formData.dicAttachments && formData.dicAttachments[fileMapType.get(108)]) {
              res.data.dicAttachments[fileMapType.get(108)].forEach((item: any) => {
                fileList3.value.push({
                  name: item.attachmentName,
                  status: "success",
                  uid: item.attachmentId,
                });
              });
            }
            if (formData.dicAttachments && formData.dicAttachments[fileMapType.get(109)]) {
              res.data.dicAttachments[fileMapType.get(109)].forEach((item: any) => {
                fileList2.value.push({
                  name: item.attachmentName,
                  status: "success",
                  uid: item.attachmentId,
                });
              });
            }
            if (formData.dicAttachments && formData.dicAttachments[fileMapType.get(110)]) {
              res.data.dicAttachments[fileMapType.get(110)].forEach((item: any) => {
                fileList4.value.push({
                  name: item.attachmentName,
                  status: "success",
                  uid: item.attachmentId,
                });
              });
            }
            if (formData.dicAttachments && formData.dicAttachments[fileMapType.get(111)]) {
              res.data.dicAttachments[fileMapType.get(111)].forEach((item: any) => {
                fileList5.value.push({
                  name: item.attachmentName,
                  status: "success",
                  uid: item.attachmentId,
                });
              });
            }
          }
        });
      }
    }
  }
);

function initScreen() {
  if (mobile.value === "mobile") {
    screenWidth.value = screenStore.screenWidth;
    itemSpan.value = 24;
  } else {
    screenWidth.value = 900;
    itemSpan.value = 10;
  }
}

onMounted(async () => {
  initScreen();
});

/**
 * 关闭弹窗
 */
function closeDialog(needRefresh: boolean) {
  emit("sendClose", needRefresh);
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  active.value = 0;
  fileList.value = [];
  fileList2.value = [];
  fileList3.value = [];
  fileList4.value = [];
  fileList5.value = [];
  baseFormRef.value.resetFields();
  baseFormRef.value.clearValidate();
}

/**
 * 项目表单提交
 */
function handleSubmit() {
  promiseFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      let attachments = [] as Int32AttachmentsForm[];
      let attachments2 = [] as Int32AttachmentsForm[];
      let attachments3 = [] as Int32AttachmentsForm[];
      let attachments4 = [] as Int32AttachmentsForm[];
      let attachments5 = [] as Int32AttachmentsForm[];
      fileList.value.forEach((item: any) => {
        if (item.status === "success") {
          if (item.response) {
            attachments.push({
              attachmentId: item.response.data,
            });
          } else {
            attachments.push({
              attachmentId: item.uid,
            });
          }
        }
      });
      fileList2.value.forEach((item: any) => {
        if (item.status === "success") {
          if (item.response) {
            attachments2.push({
              attachmentId: item.response.data,
            });
          } else {
            attachments2.push({
              attachmentId: item.uid,
            });
          }
        }
      });
      fileList3.value.forEach((item: any) => {
        if (item.status === "success") {
          if (item.response) {
            attachments3.push({
              attachmentId: item.response.data,
            });
          } else {
            attachments3.push({
              attachmentId: item.uid,
            });
          }
        }
      });
      fileList4.value.forEach((item: any) => {
        if (item.status === "success") {
          if (item.response) {
            attachments4.push({
              attachmentId: item.response.data,
            });
          } else {
            attachments4.push({
              attachmentId: item.uid,
            });
          }
        }
      });
      fileList5.value.forEach((item: any) => {
        if (item.status === "success") {
          if (item.response) {
            attachments5.push({
              attachmentId: item.response.data,
            });
          } else {
            attachments5.push({
              attachmentId: item.uid,
            });
          }
        }
      });
      formData.dicAttachments = {
        ["107"]: attachments,
        ["108"]: attachments2,
        ["109"]: attachments3,
        ["110"]: attachments4,
        ["111"]: attachments5,
      };
      if (dialogAddOrEdit.value.id > 0) {
        UpdateProjectCompleted(formData)
          .then((resp) => {
            if (resp.type === 0) {
              if (resp.success === true) {
                ElMessage.success(resp.msg);
                closeDialog(true);
              } else {
                ElMessage.warning(resp.msg);
              }
            } else {
              ElMessage.warning(resp.msg);
            }
          })
          .finally(() => (loading.value = false));
      } else {
        AddProjectCompleted(formData)
          .then((resp) => {
            if (resp.type === 0) {
              if (resp.success === true) {
                ElMessage.success(resp.msg);
                closeDialog(true);
              } else {
                ElMessage.warning(resp.msg);
              }
            } else {
              ElMessage.warning(resp.msg);
            }
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}
</script>

<style lang="scss" scoped>
:deep(.el-form-item) {
  flex-wrap: wrap;
}

:deep(.el-input) {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}
:deep(.el-cascader) {
  width: 100%;
}
:deep(.el-input__wrapper) {
  width: 100%;
}

:deep(.el-form-item__label) {
  color: #696868;
  font-size: 13px;
}
:deep(.el-upload__tip) {
  margin-left: 10px;
}
:deep(.el-step.is-simple .el-step__title) {
  font-size: 14px;
}

:deep(.el-steps--simple) {
  padding: 13px 4% !important;
}
:deep(.el-icon svg) {
  height: 1.5em;
  width: 1.5em;
}
</style>
